<?php


namespace api\controllers;


use api\components\BaseController;
use common\helpers\commonApi;
use common\helpers\PageApi;
use common\models\Classify;
use common\models\Goods;
use common\models\GoodsSpec;
use common\models\GoodsStock;
use common\models\Order;
use common\models\UserCoupon;
use Yii;

class GoodsController extends BaseController
{
    /**
     * 分类
     * @return array
     */
    public function actionClassify()
    {
        $data = Classify::find()
            ->where(['status'=>1,'delete'=>0])
            ->select(['id as c_id','name'])
            ->orderBy(['sort'=>SORT_DESC,'create_time'=>SORT_DESC])
            ->asArray()->all();
        return commonApi::message('ok',true,$data);
    }

    /**
     * 商品列表
     * @return array
     */
    public function actionGoods()
    {
        $get = Yii::$app->request->get();
        $c_id = $get['c_id']??'';
        $page = $get['page']??1;
        if (!$c_id){
            return commonApi::message('请选择分类',false);
        }
        $query = Goods::find()
            ->where(['classify_id'=>$c_id,'status'=>1,'delete'=>0])
            ->select(['id as g_id','name','main_img','(vr_sales+ac_sales) as sales','price','intr'])
            ->orderBy(['sort'=>SORT_DESC,'create_time'=>SORT_DESC]);
        $data = PageApi::apiPage($query,$page);
        $g_ids = array_column($data['data'],'g_id');
        $spec_id = GoodsSpec::find()->where(['good_id'=>$g_ids])->select(['id'])->asArray()->all();
        $spec_id = array_column($spec_id,'id');
        $stock = GoodsStock::find()
            ->where(['good_id'=>$g_ids,'spec_id'=>$spec_id,'campus_id'=>$this->campus_id])
            ->select(['sum(stock) as stock','good_id'])
            ->groupBy(['good_id'])
            ->asArray()->all();
        $stock = array_column($stock,'stock','good_id');
        foreach ($data['data'] as &$datum){
            $datum['main_img'] = commonApi::getDomain($datum['main_img']);
            $datum['stock'] = $stock[$datum['g_id']]??0;
        }
        return commonApi::message('ok',true,$data);
    }

    /**
     * 商品详情
     * @return array
     */
    public function actionGoodDetail()
    {
        $g_id = Yii::$app->request->get('g_id','');
        if (!$g_id){
            return commonApi::message('请选择查看的商品',false);
        }
        $data = Goods::find()
            ->where(['id'=>$g_id,'status'=>1,'delete'=>0])
            ->select(['id as g_id','name','price','details','imgs','intr'])
            ->asArray()->one();
        if (!$data){
            return commonApi::message('商品已下架',false);
        }
        $imgs = explode(',',$data['imgs']);
        $imgArr= [];
        foreach ($imgs as &$img){
            $img = commonApi::getDomain($img);
            $imgArr[] = [
                'img'=>$img
            ];
        }
        //规格
        $spec = [];
        if ($this->campus_id){
            $spec = GoodsSpec::find()
                ->alias('gsp')
                ->innerJoin(GoodsStock::tableName().' as gst','gst.spec_id=gsp.id and gst.campus_id='.$this->campus_id)
                ->where(['gsp.good_id'=>$data['g_id']])
                ->select(['gsp.name','gsp.price','gsp.original_price','gst.stock','gst.sales','gsp.id as spec_id'])
                ->asArray()->all();
        }
        $arr = [
            'g_id' => $data['g_id'],
            'name' => $data['name'],
            'price' => $data['price'],
            'details' => $data['details'],
            'intr' => $data['intr'],
            'imgs' => $imgArr,
            'spec' => $spec,
        ];
        return commonApi::message('ok',true,$arr);
    }

    /**
     * 计算
     * @return array
     */
    public function actionCalculation()
    {
        $post = Yii::$app->request->post();
        $data = $post['data']??'';
        $uc_id = $post['uc_id']??'';
        $delivery_method = $post['delivery_method']??1;
        if (!$data){
            return commonApi::message('请选择商品',false);
        }
        $data = json_decode($data,true);
        if (!$data){
            return commonApi::message('格式错误',false);
        }
        foreach ($data as &$datum){
            $datum['campus_id'] = $this->campus_id;
        }
        $discount_amount = 0;
        if ($uc_id) {
            $usercoupon = UserCoupon::find()
                ->where(['id' => $uc_id, 'userid' => self::$userid, 'status' => 1, 'delete' => 0, 'use' => 0])
                ->one();
            if (!$usercoupon) {
                return commonApi::message('卡券不错误', false);
            }
            $discount_amount = $usercoupon->discount_amount;
        }
        $model = new GoodsSpec();
        $result = $model->calculation($data,0,$delivery_method);
        if (!$result['success']){
            return $result;
        }
        $result['data']['goods_total']['pay_amount'] = $result['data']['goods_total']['pay_amount']-$discount_amount;
        if ($result['data']['goods_total']['pay_amount']<=0){
            $result['data']['goods_total']['pay_amount'] = 0;
        }
        $arr = [
            'discount_amount'=>$discount_amount,
            'delivery_fee'=>$result['data']['goods_total']['delivery_fee'],
            'pay_amount'=>$result['data']['goods_total']['pay_amount'],
            'total_amount'=>$result['data']['goods_total']['total_amount'],
        ];
        return commonApi::message('ok',true,$arr);
    }

    /**
     * 下单
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function actionPlaceOrder()
    {
        $post = Yii::$app->request->post();
        $model = new Order();
        return $model->placeOrder($post,self::$userid,$this->campus_id);
    }
}